﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JX.Infrastructure.Common
{
	/// <summary>
	/// 轮询算法帮助类
	/// </summary>
	public class PollingHelper<T>
	{
        /// <summary>
        /// 锁
        /// </summary>
        private readonly object _syncLock = new object();
        /// <summary>
        /// 要进行轮询的列表
        /// </summary>
        private readonly IList<T> _items;
        /// <summary>
        /// 当前访问的索引，开始是-1，因为没有人访问
        /// </summary>
        private int _currentIndex = -1;

        /// <summary>
        /// 构造器注入
        /// </summary>
        /// <param name="sequence">要进行轮询的列表</param>
        public PollingHelper(IEnumerable<T> sequence)
        {
            _items = sequence.ToList();

            if (_items.Count <= 0)
            {
                throw new ArgumentException("序列不包含元素", nameof(sequence));
            }
        }

        /// <summary>
        /// 得到下一个要访问的元素
        /// </summary>
        /// <returns></returns>
        public T GetNextItem()
        {
            lock (this._syncLock)
            {
                _currentIndex++;
                //超过数量，索引归0
                if (_currentIndex >= _items.Count)
                    _currentIndex = 0;
                return _items[_currentIndex];
            }
        }
    }
}
